import math
import os
from tensorflow import keras
import numpy as np


class NeuralNetwork:
    """
    神经网络
    """

    def __init__(self, brain) -> None:
        self.share_path = brain.share_path
        model_path = os.path.join(self.share_path, "coordinate_net.keras")
        self.model = keras.models.load_model(model_path)
        pass

    def create_next_step(
        self, car_world_angle, car_world_x, car_world_y, target_world_x, target_world_y
    ):
        angle, distance = self.get_next_step(
            car_world_x, car_world_y, target_world_x, target_world_y
        )
        angle -= car_world_angle

        angle_direction = 1
        distance_direction = 0
        if angle != 0:
            angle_direction = 1
            if angle < 0:
                angle_direction = 0
                angle = -angle

        return False, angle_direction, angle, distance_direction, distance

    def get_next_step(self, car_world_x, car_world_y, target_world_x, target_world_y):
        x = target_world_x - car_world_x
        y = target_world_y - car_world_y
        scale, data = self.normalization(x, y)
        predictions = self.model.predict(data)
        angle, distance = predictions[0][0][0], predictions[1][0][0]
        distance *= scale
        return float(angle), float(distance)

    def normalization(self, x, y):
        new_x = x
        new_y = y
        a_x = abs(x)
        a_y = abs(y)
        scale = 1
        a_max = a_x
        if a_y > a_x:
            a_max = a_y
        while True:
            if a_max <= 100:
                break
            a_max /= 10
            new_x /= 10
            new_y /= 10
            scale *= 10
        data = np.array([[new_x, new_y]])
        mean = np.array([-1.57826438e-05, 0.00000000e+00])
        std = np.array([57.82661797, 57.9356249])
        data -= mean
        data /= std
        return scale, data
